package com.ssy.lingxi.platform.manage.serviceimpl.paas;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.platform.manage.api.model.dto.shop.ShopPAASDTO;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.base.Shop;
import com.ssy.lingxi.platform.manage.repository.ShopRepository;
import com.ssy.lingxi.platform.manage.service.paas.IShopPAASService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商城 - （系统初始化）PAAS接口 - 业务实现层
 * @author fhj
 * @version 2.0.0
 * @date 2020/9/28
 */
@Slf4j
@Service
public class ShopPAASServiceImpl implements IShopPAASService {

    @Resource
    private ShopRepository shopRepository;
    @Resource
    private IRedisStringUtils redisStringUtils;

    @Override
    @Transactional
    public Wrapper<Void> add(ShopPAASDTO dto) {
        //如果为企业商城
        if(dto.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())) {
            //同环境同属性的企业商城只能有一个默认商城
            List<Shop> shopList = shopRepository.findByEnvironmentAndTypeAndProperty(
                    dto.getEnvironment(),
                    dto.getType(),
                    dto.getProperty()
            );
            if(dto.getIsDefault().equals(CommonBooleanEnum.YES.getCode()) && CollectionUtil.isNotEmpty(shopList)) {
                shopList = shopList.stream().peek(a -> a.setIsDefault(CommonBooleanEnum.NO.getCode())).collect(Collectors.toList());
                shopRepository.saveAll(shopList);
            }
        }

        //新增
        Shop shop = new Shop();
        BeanUtils.copyProperties(dto, shop);
        shopRepository.saveAndFlush(shop);

        //更新缓存信息
        updateRedisInfo(shop);

        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> update(ShopPAASDTO dto) {
        //如果为企业商城
        if(dto.getType().equals(ShopTypeEnum.ENTERPRISE.getCode())) {
            List<Shop> shopList = shopRepository.findByEnvironmentAndType(
                    dto.getEnvironment(),
                    dto.getType()
            );
            if (dto.getIsDefault().equals(CommonBooleanEnum.YES.getCode()) && CollectionUtil.isNotEmpty(shopList)) {
                shopList = shopList.stream().peek(a -> a.setIsDefault(CommonBooleanEnum.NO.getCode())).collect(Collectors.toList());
                shopRepository.saveAll(shopList);
            }
        }

        //获取商城
        Shop shop = shopRepository.findById(dto.getId()).orElse(null);
        if(shop == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        //修改
        shop.setName(dto.getName());
        shop.setUrl(dto.getUrl());
        shop.setLogoUrl(dto.getLogoUrl());
        shop.setDescribe(dto.getDescribe());
        shop.setIsDefault(dto.getIsDefault());
        shop.setMemberOperate(dto.getMemberOperate());
        shop.setOpenMro(dto.getOpenMro());
        shopRepository.saveAndFlush(shop);

        //更新缓存信息
        updateRedisInfo(shop);

        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> stopAndStart(ShopPAASDTO dto) {
        //获取商城
        Shop shop = shopRepository.findById(dto.getId()).orElse(null);
        if(shop == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        //修改
        shop.setState(dto.getState());
        shopRepository.saveAndFlush(shop);

        //更新缓存信息
        if(dto.getState().equals(CommonBooleanEnum.YES.getCode())) {
            updateRedisInfo(shop);
        }else{
            redisStringUtils.hDel(Constants.REDIS_KEY_SHOP, String.valueOf(dto.getId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
        }

        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> delete(ShopPAASDTO dto) {
        //获取商城
        Shop shop = shopRepository.findById(dto.getId()).orElse(null);
        if(shop == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        //删除
        shopRepository.delete(shop);

        //清除缓存信息
        redisStringUtils.hDel(Constants.REDIS_KEY_SHOP, String.valueOf(dto.getId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);


        return Wrapper.success();
    }

    /**
     * 更新redis中的数据
     */
    private void updateRedisInfo(Shop shop) {
        Map<String, String> map = new HashMap<>();
        map.put(String.valueOf(shop.getId()), JSONUtil.toJsonStr(shop));
        redisStringUtils.hMSet(Constants.REDIS_KEY_SHOP, map, Constants.REDIS_PLATFORM_MANAGE_INDEX);
    }
}
